import config
from collections import namedtuple
import os
LogBlocks =  namedtuple('LogBlocks', ['projectName', 'lineBlocks', 'lines'])

class LoadLog():
    '''
        加载 make VERBOSE=1 构建日志，并分割各个目标在日志中的位置(lines)
    '''
    SLICESTR = config.SLICE_TARET

    def __init__(self, logPath):
        self._logPath = logPath
        self._projectName = os.path.split(self._logPath)[-1].rstrip()[ : os.path.split(self._logPath)[-1].rstrip().find('.')]

    def __GetAllLog(self):
        '''读取日志所有行'''
        with open(self._logPath, 'r') as logf:
            self._lines = logf.readlines()
        return len(self._lines)

    def __SliceLinesByTarget(self, sliceStr):
        '''获取各个构建目标的日志分割成块'''
        lineSlices = [self._lines.index(line) + 1 for line in self._lines if line.find(sliceStr) > 0 and self._lines.index(line) > 0]
        # for i in lineSlices:
        #     print('{} {}'.format(i, self._lines[i]))
        lineSlices.insert(0, 0)
        self._lineBlocks = [(lineSlices[i], lineSlices[i+1]) for i in range(len(lineSlices) - 1)]
        # print(len(self._lineBlocks))
        return len(self._lineBlocks)

    def GetTargetLineBlock(self, sliceStr = SLICESTR):
        '''
            返回各个target构建的日志块和全部日志
        '''
        self.__GetAllLog()
        self.__SliceLinesByTarget(sliceStr)
        return LogBlocks(self._projectName, self._lineBlocks, self._lines)


if __name__ == "__main__":
    loader = LoadLog('./libtiff.log')
    lineBlocks = loader.GetTargetLineBlock()
    print(lineBlocks)
